package it.csi.finregio.finreges.util;

import it.csi.finregio.finreges.presentation.form.SchedaForm;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;

public class RequestUtil {

	public static ActionForm fillActionForm(HttpServletRequest request,ActionForm form){
		Method[] methods = form.getClass().getMethods();
		Map mthMap = new HashMap();
		for (int i = 0; i < methods.length; i++) {
			Method m = methods[i];
			String name = m.getName();
			if(name.length()>=3){
				name = name.substring(0,3);
				if(name.equals("set")){
					mthMap.put(m.getName(), m);
				}
			}
		}
		Enumeration parameterNames = request.getParameterNames();
		try {
			while (parameterNames.hasMoreElements()) {
				String name = (String) parameterNames.nextElement();
				String value = request.getParameter(name);
				Method m = (Method) mthMap.get("set"+StringUtils.capitalize(name));
				if(m!=null){
					m.invoke(form, new Object[]{value});
				}
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return form;
	}
	
	public static void main(String[] args) {
		SchedaForm sc = new SchedaForm();
	}
}
